package com.bz.xtcx.manager.utils;

import com.linkage.netmsg.NetMsgclient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SmsSender {

	private static final Logger logger = LoggerFactory.getLogger(SmsSender.class);

    private NetMsgclient smsClient = new NetMsgclient();
    private SmsReceiveWorker smsReceiveWorker = new SmsReceiveWorker();

    @Value("${sms.user}")
    private String smsUser;

    @Value("${sms.pwd}")
    private String smsPwd;

    @Value("${sms.ip}")
    private String smsIp;

    @Value("${sms.port}")
    private String smsPort;

    private boolean isInit = false;

    private synchronized void init() {
        if (!isInit) {
            smsClient = smsClient.initParameters(smsIp, Integer.parseInt(smsPort), smsUser, smsPwd, smsReceiveWorker);
            try {
                boolean isAuth = smsClient.anthenMsg(smsClient);
                if (isAuth) {
                    logger.info("短信发送工具初始化完成");
                    isInit = true;
                } else {
                    logger.error("短信发送工具初始化失败");
                }
            } catch (Exception ex) {
                logger.error("短信发送工具初始化异常", ex);
            }
        }
    }

    public synchronized boolean sendSms(String to, String content) {
        init();
        try {
            String ret = smsClient.sendMsg(smsClient, 0, to, content, 1);
            logger.info("短信发送结果: " + ret);
            return true;
        } catch (Exception ex) {
            logger.error("短信发送发生异常", ex);
        }
        return false;
    }

    public static String makeSmsMsg(String template, String[] param) {
        String msg = template;
        for (int i = 0; i < param.length; i++) {
            msg = msg.replace("%" + i + "%", param[i]);
        }
        return msg;
    }
}
